﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using FormControllers;
using Ecopsy.Tools;
using AgencyEntityLib.BaseEntity;
using SqlLibrary;
using Ecopsy.DataTier.SqlLibrary;


public partial class iFrameAdmin_Constractions : iAdmin_Page
{   
    #region Private
    private void MyBind()
    {
        ObjectDS_PF ODS = new ObjectDS_PF(GetLvList);
        lvConstractions.DataSource = ODS.ImAsObjectDataSource;        
        lvConstractions.DataBind();
        pnlCaption.DataBind();
    }



    protected void OnInit()
    {
        ctlFilterSave1.SaveOnClick = ctlFilterSave1_SaveOnClick;
        ctlFilterSave1.OkOnClick = ctlFilterSave1_OkOnClick;
        ctlFilterSave1.FilterType = Filter.FilterType.ConstractionsList;
        ctlFilterSave1.AddKey = string.Empty;
        

        ctlFilterBar1.OnFindClik = ctlFilterBar1_OnFindClik;
        ctlFilterBar1.OnFilterListClik = ctlFilterBar1_OnFilterListClik;
        ctlFilterBar1.OnFilterSaveClik = ctlFilterBar1_OnFilterSaveClik;
        ctlFilterBar1.HintServiceMethod = "GetConstractionsParams";


        ctlFilterList1.OnApp_Click = ctlFilterList1_OnApp_Click;
        ctlFilterList1.FilterType = Filter.FilterType.ConstractionsList;
        ctlFilterSave1.AddKey = string.Empty;

        ModalPopupext_FilterSave.DataBind();
        ModalPopupext_FilterList.DataBind();
    }

    private bool ctlFilterList1_OnApp_Click(ListWhere _Where)
    {
        Where = _Where;
        ctlFilterBar1.Lexeme = _Where.ListLoadStatment.Lexeme;
        MyBind();
        //ctlFilterSave1.DataBind();
        //ctlFilterBar1.DataBind();
        //lvConstractions.DataBind();
        return true;
    }

    private bool ctlFilterBar1_OnFilterSaveClik()
    {
        ModalPopupext_FilterSave.Show();
        return true;
    }

    private bool ctlFilterBar1_OnFilterListClik()
    {
        ctlFilterList1.MyDataBind();
        ModalPopupext_FilterList.Show();
        return true;
    }

    private ListWhere ctlFilterSave1_SaveOnClick()
    {
        return (ListWhere)Where.Clone();
    }

    private bool ctlFilterSave1_OkOnClick()
    {
        ModalPopupext_FilterSave.DataBind();
        ModalPopupext_FilterSave.Hide();
        return true;
    }

    private bool ctlFilterBar1_OnFindClik(string sFindStr)
    {
        Where.ListLoadStatment.Lexeme = ctlFilterBar1.Lexeme;
        MyBind();
        return true;
    }


    #region SavePanel

    protected string GetTargetControlID_FilterSave()
    {
        return ctlFilterBar1.BtnAddFilter_ClientID;
    }

    public string GetOkControlID_FilterSave()
    {

        return ctlFilterSave1.btnSave_ClientID;
    }

    public string GetCancelControlID_FilterSave()
    {

        return ctlFilterSave1.BtnCancel_ClientID;
    }

    #endregion

    #region ListPanel

    protected string GetTargetControlID_FilterList()
    {
        return ctlFilterBar1.BtnFilterList_ClientID;
    }

    public string GetOkControlID_FilterList()
    {

        return ctlFilterList1.btnSave_ClientID;
    }

    public string GetCancelControlID_FilterList()
    {

        return ctlFilterList1.BtnCancel_ClientID;
    }

    #endregion




    private string ConstractionTypeID
    {
        get { return (Request.QueryString[qConstractionTypeID]=="3E5A3086-2A46-4051-9CE8-934976E40AC8"?string .Empty :Request.QueryString[qConstractionTypeID]); }
    }
    #endregion   
        
    protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
        { 
            // сконфигурировать where             
            Where.SortCondition.SortField = "ConstractionTypeName";
            ConstractionList.sqlLoadStatment w = (ConstractionList.sqlLoadStatment)Where.ListLoadStatment;
            w.ParamValueList_SearchOption = vPropertyOfList.Options.Value;
            w.ParamValueList.Clear(); 
            if(!string.IsNullOrEmpty (ConstractionTypeID ) )          
                w.ParamValueList.Add(new vPropertyOfList.ParamListItem() { Param = string.Empty, Value = ConstractionTypeID });
                        
            MyBind();
            
        }

        OnInit();
        
    }
    
    protected void EditButton_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;        
        Response.Redirect ("iFrameAdmin_ConstractionEditor.aspx?" + qConstractionID + "=" + btn.CommandArgument);
    }
    
    protected void AddButton_Click(object sender, EventArgs e)
    {   
        bool isEnabled = true;
        string sUrlKey = GlobalConstants.SiteMapItem_iFrameAdmin_ConstractionEditor;
        iPageController.SetPageUrl(ref sUrlKey, ref isEnabled);
        string s = "PageProcessor.aspx?Page=" + sUrlKey + ".aspx?" + "ConstractionID=" + GlobalConstants.qPrefNEW_RECORD + Guid.NewGuid().ToString() + GlobalConstants.qParamSplitter+qConstractionTypeID+"="+ConstractionTypeID ;
        Response.Redirect(s);
    }


    protected string OnFullSizeClick(string SideId)
    {
        object r = this.lvConstractions.EditItem;       
            return "window.open('PageProcessor.aspx?Page=iFrameOperation_SideBrowse.aspx?" +
            qConstractionID + "="
            + CurrentEditID + GlobalConstants.qParamSplitter
            + qSideID + "=" + SideId + "')";
        
    }
    
    /// <summary>
    /// Поиск
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>    
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        //string sFlt = txtSearch.Text;
        ////int errPosition = -1;
        //////if (!ExpressionChecker.CheckStatment(ref sFlt, ref errPosition))
        ////{
        ////    ScriptManager.RegisterStartupScript(this, GetType(), "AlertBadFiltr", "alert('Ошибочное выражение фильтрации');", true);
        ////    return;
        ////}

        //Where.ListLoadStatment.Lexeme = sFlt;
        //MyBind();
    }

    protected string TxtSerchValue
    {
        get { return Where.ListLoadStatment.Lexeme ; }       
    }
      
  
    protected string sOnAddBtnClick
    {
        get 
        {
            return "OnStartUpWizard("+GlobalConstants.qPrefNEW_RECORD+Guid.NewGuid ().ToString ()  +"');";            
        }
    
    }

    /// <summary>
    /// Источник конструкций
    /// </summary>
    /// <param name="startRowIndex"></param>
    /// <param name="maximumRows"></param>
    /// <param name="RowCount"></param>
    /// <returns></returns>
    protected lvConstraction[] GetLvList(int startRowIndex, int maximumRows, out int RowCount)
    {        
        Constraction[] l = GetList(
                                    Where,
                                    out RowCount,
                                    startRowIndex,
                                    maximumRows
                                    );
        lvConstraction[] r = new lvConstraction[l.Length];

        for (int i = 0; (i < l.Length); i++)
        {
            r[i] = new lvConstraction(l[i]);
        }                
        
        //заряжаем comparer функцией сортировки 
        Where.SortCondition.fnOrderBy = SortFunctions.fOrderBy ;
        // Сортируем
        Array.Sort(r, Where.SortCondition);
        return r;
    }




    wsConstractions _ws_Constraction = (wsConstractions)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Constraction];                    
    
    public Constraction[] GetList(
                                            object _Where,
                                            out int RowCount,
                                            int startRowIndex,
                                            int endRowIndex
                                        )
    {
        ListWhere w = (ListWhere)_Where;        
        w.ListLoadStatment.StartRowIndex = startRowIndex;
        w.ListLoadStatment.EndRowIndex = endRowIndex;                
        ConstractionList l = _ws_Constraction.GetConstractionList((ConstractionList.sqlLoadStatment) w.ListLoadStatment);
        RowCount = l.OutputRwCnt;
        return l.ToList<Constraction>().ToArray<Constraction>();

    }

    protected override ListWhere Where
    {
        get
        {
            return f_Where(new ConstractionList.sqlLoadStatment(), "Name");
        }
        set
        {
            f_SetWhere(value); 

        }
    }

    protected void lvSort(object sender, EventArgs e)
    {
        f_lvSort(sender, lvConstractions, MyBind); 
    }

    protected void EditConstracton(object sender, EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        bool isEnabled = true;
        string sUrlKey = GlobalConstants.SiteMapItem_iFrameAdmin_ConstractionEditor;
        iPageController.SetPageUrl(ref sUrlKey, ref isEnabled);
        string s = "PageProcessor.aspx?Page=" + sUrlKey + ".aspx?" + "ConstractionID=" + btn.CommandArgument ;
        Response.Redirect(s);
         
    }


   
    protected string qDepartamentID_Value
    {
        get
        {
            return Request[qDepartmentID];
        }
    }
    
    /// <summary>
    /// класс визуализации 
    /// </summary>
    protected class lvConstraction : grdConstraction 
    {
        public lvConstraction(Constraction Constr) : base(Constr) { }
        public string OnDblclick
        {
            get { return "OnDblclickGrid('" + _Constraction.ID + "');"; }
        }
    }
    

    protected bool PagerVisible 
    {
        get {
            return this.DataPager.PageSize < this.DataPager.TotalRowCount; 
        }
    }
   
    protected void lvConstractions_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    
    protected void lvConstractions_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        ListView lv = (ListView)sender;
        switch (e.CommandName)
        {
            case "Edit":
                {
                      
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = this .DataPager .CalculateRealEditIndex (d.DataItemIndex);                    
                     
                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    lv.EditIndex = -1;
                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }
            case "Cancel":
                {
                    lv.EditIndex = -1;
                    break;
                }
        }

        ObjectDS_PF ODS = new ObjectDS_PF(GetLvList);
        lvConstractions.DataSource = ODS.ImAsObjectDataSource; 
        lv.DataBind();
        


    }
    
    protected void lvConstractions_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        
    }

    protected  lvConstraction Get_lvConstraction(string ConstractionId)
    {
        return new lvConstraction (_ws_Constraction.GetConstraction(ConstractionId)); 
    }

    private string CurrentEditID = string.Empty; 
    protected void lvConstractions_ItemDataBound(object sender, ListViewItemEventArgs e)
    {

        ListViewDataItem item = (ListViewDataItem)e.Item;

        if (lvConstractions.EditIndex != item.DisplayIndex) return;//? это редактируемая строка 
        lvConstraction Constr= (lvConstraction)item.DataItem  ;
        CurrentEditID = Constr.ID; 
        GridView grd = (GridView)item.FindControl("grdSides");
        grd.DataSource = Constr.SideList.ToList <Side >();
        grd.DataBind(); 
    }
    
    protected void lvConstractions_PagePropertiesChanged(object sender, EventArgs e)
    {
   
                MyBind();
    }
}
